#include "Socket.hpp"
#include "Protocol.hpp"
#include <iostream>
#include <string>
#include <cstdlib>

static void Usage(const std::string &proc)
{
    std::cout << "/nUsage:  ./" << proc << " serverip serverport" << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3) {
        Usage(argv[0]);
        exit(0);
    }
    
    std::string clientip = argv[1];
    uint16_t clientport = std::stoi(argv[2]);

    Sock sockfd;
    sockfd.Socket();
    bool r = sockfd.Connect(clientip, clientport);
    if (!r)  return -1;

    srand(time(nullptr) ^ getpid());
    const std::string opers = "+-*/%@&";

    std::string inbuff_stream; // 接收server端的结果
    std::string package;  // 存储封装后的报文
    int cnt = 1;
    while (cnt < 10)
    {
        std::cout << "------------------- 第" << cnt << "次测试 -------------------" << std::endl;
        int x = rand() % 100;
        usleep(1234);
        int y = rand() % 50;
        usleep(1234);
        char op = opers[rand()%opers.size()];
        std::cout << "Debug: " << x << op << y << std::endl;
        Request req(x, y, op);

        // 1. 序列化
        req.Serialize(&package);
        // 2. 封装有效载荷
        package = Encode(package);
        // 3. 将封装后的报文发送给server端
        write(sockfd.GetFd(), package.c_str(), package.size());
        // 4. 接收server端的回复
        char buffer[128];
        ssize_t n = read(sockfd.GetFd(), buffer, sizeof(buffer));
        if (n > 0)
        {
            buffer[n] = 0;
            inbuff_stream += buffer;
            std::string content;
            // 5. 解包,提取报文中的有效载荷
            bool rr = Decode(inbuff_stream, &content);
            if (!rr)  continue;;
            // 6. 反序列化
            Response resp;
            rr = resp.Deserialize(content);
            if (!rr) continue;;
            std::cout << content << std::endl;
            resp.DebugPrint();  // 打印结果
        }
        inbuff_stream.clear();
        package.clear();
        std::cout << "-----------------------------------------------" << std::endl;
        ++cnt;
        sleep(1);
    }
    return 0;
}